package com.selune.online.ordering.system.project.tenant.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import static com.selune.online.ordering.system.common.util.FindUserUtils.getCustomerByUserName;
import static com.selune.online.ordering.system.common.util.FindUserUtils.getCustomerUserById;
import static com.selune.online.ordering.system.common.util.FindUserUtils.getTenantByTenantName;
import static com.selune.online.ordering.system.common.util.FindUserUtils.getTenantUserById;
import com.selune.online.ordering.system.project.api.base.entity.CustomerLogin;
import com.selune.online.ordering.system.project.api.base.entity.CustomerUserInfo;
import com.selune.online.ordering.system.project.api.base.entity.TenantUserInfo;
import com.selune.online.ordering.system.project.api.base.exception.ParamsException;
import com.selune.online.ordering.system.project.api.base.exception.UserException;
import com.selune.online.ordering.system.project.api.base.response.Response;
import com.selune.online.ordering.system.project.api.mapper.CustomerLoginMapper;
import com.selune.online.ordering.system.project.api.mapper.CustomerUserInfoMapper;
import com.selune.online.ordering.system.project.api.mapper.TenantUserInfoMapper;
import com.selune.online.ordering.system.project.api.pojo.user.customer.dto.CustomerUserSearchDTO;
import com.selune.online.ordering.system.project.api.pojo.user.customer.vo.CustomerUserInfoVO;
import com.selune.online.ordering.system.project.api.pojo.user.tenant.vo.TenantUserInfoVO;
import com.selune.online.ordering.system.project.api.service.user.IUserManageService;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created with IntelliJ IDEA.
 *
 * @author xiaoyp
 * @date 2020/3/23
 * <p>
 * Description:
 */
@Service
@Slf4j
public class UserManageServiceImpl implements IUserManageService {
	
	@Resource
	private CustomerUserInfoMapper customerUserInfoMapper;
	@Resource
	private TenantUserInfoMapper tenantUserInfoMapper;
	@Resource
	private CustomerLoginMapper customerLoginMapper;
	
	@Override
	public Response<CustomerUserInfoVO> selectOneCustomerUser(String userName) {
		CustomerUserInfo customerUserInfo = getCustomerByUserName(customerUserInfoMapper, userName).getData();
		CustomerUserInfoVO customerUserInfoVO = new CustomerUserInfoVO();
		BeanUtils.copyProperties(customerUserInfo, customerUserInfoVO);
		
		log.info("ACCESS_LOG[]CustomerUserServiceImpl[]selectOneUser[]get user info success!");
		return Response.success(customerUserInfoVO);
	}
	
	@Override
	public Response<List<CustomerUserInfoVO>> selectAllCustomerUser(CustomerUserSearchDTO customerUserSearchDTO) {
		List<CustomerUserInfo> customerUserInfoList = customerUserInfoMapper.selectList(
			Wrappers.<CustomerUserInfo>lambdaQuery()
				.orderByAsc(CustomerUserInfo::getCreateTime)
				.eq(CustomerUserInfo::getIsDelete, Boolean.FALSE)
				.eq(StringUtils.isNotBlank(customerUserSearchDTO.getUserName()), CustomerUserInfo::getUserName,
					customerUserSearchDTO.getUserName())
				.eq(null != customerUserSearchDTO.getUserPhone(), CustomerUserInfo::getUserPhone,
					customerUserSearchDTO.getUserPhone())
				.eq(StringUtils.isNotBlank(customerUserSearchDTO.getUserEmail()), CustomerUserInfo::getUserEmail,
					customerUserSearchDTO.getUserEmail())
		);
		List<CustomerUserInfoVO> customerUserInfoVOList = new ArrayList<>(customerUserInfoList.size());
		
		customerUserInfoList.forEach(tenantUserInfo -> {
			CustomerUserInfoVO customerUserInfoVO = new CustomerUserInfoVO();
			BeanUtils.copyProperties(tenantUserInfo, customerUserInfoVO);
			customerUserInfoVOList.add(customerUserInfoVO);
		});
		
		return Response.success(customerUserInfoVOList);
	}
	
	@Override
	public Response<Page<CustomerUserInfoVO>> pageAllCustomerUser(Integer current, Integer size,
	                                                              CustomerUserSearchDTO customerUserSearchDTO) {
		int newCurrent = null == current ? 1 : current;
		int pageSize = null == size ? 10 : size;
		Page<CustomerUserInfo> page = new Page<>(newCurrent, pageSize);
		Page<CustomerUserInfo> customerUserInfoPage = customerUserInfoMapper.selectPage(
			page,
			Wrappers.<CustomerUserInfo>lambdaQuery()
				.orderByAsc(CustomerUserInfo::getCreateTime)
				.eq(CustomerUserInfo::getIsDelete, Boolean.FALSE)
				.eq(StringUtils.isNotBlank(customerUserSearchDTO.getUserName()), CustomerUserInfo::getUserName,
					customerUserSearchDTO.getUserName())
				.eq(null != customerUserSearchDTO.getUserPhone(), CustomerUserInfo::getUserPhone,
					customerUserSearchDTO.getUserPhone())
				.eq(StringUtils.isNotBlank(customerUserSearchDTO.getUserEmail()), CustomerUserInfo::getUserEmail,
					customerUserSearchDTO.getUserEmail())
		);
		Page<CustomerUserInfoVO> customerUserInfoVoPage = new Page<>();
		BeanUtils.copyProperties(customerUserInfoPage, customerUserInfoVoPage);
		
		return Response.success(customerUserInfoVoPage);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Response<Boolean> deleteCustomerUserById(Long userId) {
		getCustomerUserById(customerUserInfoMapper, userId);
		
		int result = customerUserInfoMapper.update(
			null,
			Wrappers.<CustomerUserInfo>lambdaUpdate()
				.eq(CustomerUserInfo::getUserId, userId)
				.set(CustomerUserInfo::getIsDelete, Boolean.TRUE)
		);
		int result2 = customerLoginMapper.update(
			null,
			Wrappers.<CustomerLogin>lambdaUpdate()
				.eq(CustomerLogin::getUserId, userId)
				.set(CustomerLogin::getIsDelete, Boolean.TRUE)
		);
		if (result == 1 && result2 == 1) {
			return Response.success("用户删除成功!", Boolean.TRUE);
		} else {
			throw new  UserException("用户删除失败");
		}
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Response<Boolean> deleteCustomerUserByIds(List<Long> userIds) {
		if (userIds.size() == 0 || CollectionUtils.isEmpty(userIds)) {
			log.error("ACCESS_LOG[]CustomerUserServiceImpl[]deleteUserByIds[]user ids is null!");
			throw new ParamsException("user.ids.is.null");
		}
		
		int result = customerUserInfoMapper.deleteBatchIds(userIds);
		if (result >= 0) {
			return Response.success("用户删除成功!", Boolean.TRUE);
		} else {
			return Response.error("用户删除失败");
		}
	}
	
	@Override
	public Response<TenantUserInfoVO> selectOneTenantUser(String tenantName) {
		TenantUserInfo tenantUserInfo = getTenantByTenantName(tenantUserInfoMapper, tenantName).getData();
		
		TenantUserInfoVO tenantUserInfoVO = new TenantUserInfoVO();
		BeanUtils.copyProperties(tenantUserInfo, tenantUserInfoVO);
		
		log.info("ACCESS_LOG[]TenantUserServiceImpl[]selectOneUser[]get tenant info success!");
		return Response.success(tenantUserInfoVO);
	}
	
	@Override
	public Response<List<TenantUserInfoVO>> selectAllTenantUser() {
		List<TenantUserInfo> tenantUserInfoList = tenantUserInfoMapper.selectList(null);
		List<TenantUserInfoVO> tenantUserInfoVOList = new ArrayList<>(tenantUserInfoList.size());
		
		tenantUserInfoList.forEach(tenantUserInfo -> {
			TenantUserInfoVO tenantUserInfoVO = new TenantUserInfoVO();
			BeanUtils.copyProperties(tenantUserInfo, tenantUserInfoVO);
			tenantUserInfoVOList.add(tenantUserInfoVO);
		});
		
		return Response.success(tenantUserInfoVOList);
	}
	
	@Override
	public Response<Page<TenantUserInfoVO>> pageAllTenantUser(Integer current, Integer size) {
		int pageSize = null == size ? 10 : size;
		
		Page<TenantUserInfo> page = new Page<>(current, pageSize);
		Page<TenantUserInfo> tenantUserInfoPage = tenantUserInfoMapper.selectPage(
			page, Wrappers.<TenantUserInfo>lambdaQuery().orderByAsc(TenantUserInfo::getCreateTime));
		Page<TenantUserInfoVO> tenantUserInfoVoPage = new Page<>();
		BeanUtils.copyProperties(tenantUserInfoPage, tenantUserInfoVoPage);
		
		return Response.success(tenantUserInfoVoPage);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Response<Boolean> deleteTenantUserById(Long tenantId) {
		getTenantUserById(tenantUserInfoMapper, tenantId);
		
		int result = tenantUserInfoMapper.deleteById(tenantId);
		if (result == 1) {
			return Response.success("商户删除成功!", Boolean.TRUE);
		} else {
			return Response.error("商户删除失败");
		}
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Response<Boolean> deleteTenantUserByIds(List<Long> tenantIds) {
		if (tenantIds.size() == 0 || CollectionUtils.isEmpty(tenantIds)) {
			log.error("ACCESS_LOG[]TenantUserServiceImpl[]deleteUserByIds[]tenant ids is null!");
			throw new ParamsException("tenant.ids.is.null");
		}
		
		int result = tenantUserInfoMapper.deleteBatchIds(tenantIds);
		if (result >= 0) {
			return Response.success("商户删除成功!", Boolean.TRUE);
		} else {
			return Response.error("商户删除失败");
		}
	}
	
}
